package com.segi.view.xlistview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.segi.view.R;

import cn.segi.framework.util.WindowDispaly;


/**
 * The header view for {@link com.segi.view.xlistview.XListView} and
 * {@link com.segi.view.xlistview.XScrollView}
 *
 * @author markmjw
 * @date 2013-10-08
 */
public class XHeaderView extends LinearLayout {
    public final static int STATE_NORMAL = 0;
    public final static int STATE_READY = 1;
    public final static int STATE_REFRESHING = 2;
    public final static int STATE_REFRESED = 3;

    private final int ROTATE_ANIM_DURATION = 180;

    private int mState = STATE_NORMAL;

    private LinearLayout mContainer;

    /**
     * 标准的加载视图
     */
    private ProgressBar mProgressBar;
    private TextView mHintTextView;
    private TextView mHeaderTime;
    private ImageView mArrowImageView;
    private Animation mRotateUpAnim;
    private Animation mRotateDownAnim;

    /**
     * 风车加载模式
     */
    private View windmillLayout;//下拉太阳
    private ImageView sunImg;//下拉太阳
    private ImageView staticWillmillImg;//静止的风车
    private ImageView activityWindmillImg;//转动的风车
    private int mFirstImgHeight;
    private AnimationDrawable mProgressAnim;

    /**
     * 模仿某宝的加载视图
     */
    private TextView mGradientHintTextView, mGradientTxt;
    private GradientView mGradientView;

    //头部刷新的类型，1为默认样式，2为大风车，3为模仿某宝模式
    private int mHeaderType = 3;

    public final static int COMMON_HEADER = 1;

    public final static int WINDWILL_HEADER = 2;

    public final static int GRADIENT_HEADER = 3;

    private boolean mIsFirst;
    //圆形进度条松开动画
    private RotateAnimation refreshingAnimation;
    //刷新的条数
    private String txtSize;
    private Context mContext;

    public XHeaderView(Context context) {
        super(context);
        initView(context);
    }

    public XHeaderView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    private void initView(Context context) {
        this.mContext = context;
        // Initial set header view height 0
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, 0);
        if (mHeaderType == COMMON_HEADER) {
            mContainer = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.vw_header_v2_common, null);//_v2
            addView(mContainer, lp);
            setGravity(Gravity.BOTTOM);

            mArrowImageView = (ImageView) findViewById(R.id.header_arrow);
            mHintTextView = (TextView) findViewById(R.id.header_hint_text);
            mProgressBar = (ProgressBar) findViewById(R.id.header_progressbar);
            mHeaderTime = (TextView) findViewById(R.id.header_hint_time);
            mRotateUpAnim = new RotateAnimation(0.0f, -180.0f, Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0.5f);
            mRotateUpAnim.setDuration(ROTATE_ANIM_DURATION);
            mRotateUpAnim.setFillAfter(true);
            mRotateDownAnim = new RotateAnimation(-180.0f, 0.0f, Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0.5f);
            mRotateDownAnim.setDuration(ROTATE_ANIM_DURATION);
            mRotateDownAnim.setFillAfter(true);
        } else if (mHeaderType == WINDWILL_HEADER) {
            mContainer = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.vw_header_v2_windwill, null);//_v2
            addView(mContainer, lp);
            setGravity(Gravity.BOTTOM);

            windmillLayout = findViewById(R.id.header_content);
            sunImg = (ImageView) findViewById(R.id.animation_sun);
            staticWillmillImg = (ImageView) findViewById(R.id.animation_windmill);
            activityWindmillImg = (ImageView) findViewById(R.id.animation_windmill_active);
            mProgressAnim = (AnimationDrawable) activityWindmillImg.getDrawable();

            int height = (int) ((160 / 750f) * WindowDispaly.getWidth());
            int width = WindowDispaly.getWidth();

            FrameLayout.LayoutParams params4 = (FrameLayout.LayoutParams) sunImg.getLayoutParams();
            params4.height = (int) ((38 / 750f) * WindowDispaly.getWidth());
            params4.width = (int) ((38 / 750f) * WindowDispaly.getWidth());
            params4.setMargins((int) (232 * WindowDispaly.getWidth() / 750f), (int) (height * 0.1f), 0, 0);
            sunImg.setLayoutParams(params4);

            LayoutParams params = (LayoutParams) windmillLayout.getLayoutParams();
            params.height = height;
            params.width = WindowDispaly.getWidth();
            windmillLayout.setLayoutParams(params);

            FrameLayout.LayoutParams params2 = (FrameLayout.LayoutParams) staticWillmillImg.getLayoutParams();
            params2.height = (int) ((114 / 750f) * WindowDispaly.getWidth());
            params2.width = (int) ((114 / 750f) * WindowDispaly.getWidth());
            params2.setMargins((int) ((width / 750f) * 341), (int) ((height / 160f) * 19), 0, 0);
            staticWillmillImg.setLayoutParams(params2);

            FrameLayout.LayoutParams params3 = (FrameLayout.LayoutParams) activityWindmillImg.getLayoutParams();
            params3.height = (int) ((114 / 750f) * WindowDispaly.getWidth());
            params3.width = (int) ((114 / 750f) * WindowDispaly.getWidth());
            params3.setMargins((int) ((width / 750f) * 341), (int) ((height / 160f) * 19), 0, 0);
            activityWindmillImg.setLayoutParams(params3);
        } else if (mHeaderType == GRADIENT_HEADER) {
            //模仿某宝类型
            mContainer = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.vw_header_v2_gradient, null);
            addView(mContainer, lp);
            setGravity(Gravity.BOTTOM);

            mGradientTxt = (TextView) findViewById(R.id.gradient_txt);
            mGradientHintTextView = (TextView) findViewById(R.id.gradient_header_hint_text);
            mGradientView = (GradientView) findViewById(R.id.gradient_header_view);
            mGradientView.setProgress(90);

            refreshingAnimation = (RotateAnimation) AnimationUtils.loadAnimation(context, R.anim.rotating);
            LinearInterpolator lir = new LinearInterpolator();
            refreshingAnimation.setInterpolator(lir);
        }


    }


    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        int w = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        int h = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        mContainer.measure(w, h);
        mFirstImgHeight = mContainer.getMeasuredHeight();

    }

    /**
     * 加载的条数
     * @param txtSize
     */
    public void setRefreshSize(String txtSize) {
        this.txtSize = txtSize;
    }

    @SuppressLint("SetTextI18n")
    public void setState(int state) {
        if (state == mState && mIsFirst) {
            mIsFirst = true;
            return;
        }
        if (mHeaderType == COMMON_HEADER) {
            //默认下拉样式
            if (state == STATE_REFRESHING) {
                // show progress
                mArrowImageView.clearAnimation();
                mArrowImageView.setVisibility(View.INVISIBLE);
                mProgressBar.setVisibility(View.VISIBLE);
            } else {
                // show arrow image
                mArrowImageView.setVisibility(View.VISIBLE);
                mProgressBar.setVisibility(View.INVISIBLE);
            }

            switch (state) {
                case STATE_NORMAL:
                    if (mState == STATE_READY) {
                        mArrowImageView.startAnimation(mRotateDownAnim);
                    }

                    if (mState == STATE_REFRESHING) {
                        mArrowImageView.clearAnimation();
                    }

                    mHintTextView.setText(R.string.header_hint_refresh_normal);
                    break;

                case STATE_READY:
                    if (mState != STATE_READY) {
                        mArrowImageView.clearAnimation();
                        mArrowImageView.startAnimation(mRotateUpAnim);
                        mHintTextView.setText(R.string.header_hint_refresh_ready);
                    }
                    break;

                case STATE_REFRESHING:
                    mHintTextView.setText(R.string.header_hint_refresh_loading);
                    break;

                default:
                    break;
            }

        } else if (mHeaderType == WINDWILL_HEADER) {
            //大风车样式下拉
            if (state == STATE_REFRESHING) {
                staticWillmillImg.setVisibility(GONE);
                activityWindmillImg.setVisibility(VISIBLE);
            } else {
                staticWillmillImg.setVisibility(VISIBLE);
                activityWindmillImg.setVisibility(GONE);
//                if (mProgressAnim.isRunning()) {
//                    mProgressAnim.stop();
//                }
            }
            switch (state) {
                case STATE_NORMAL:
                    if (mState == STATE_READY) {
                        staticWillmillImg.setVisibility(VISIBLE);
                    }
                    if (mState == STATE_REFRESHING) {
                        if (mProgressAnim.isRunning()) {
                            mProgressAnim.stop();
                        }
                    }
//                    mHintTextView.setText(R.string.header_hint_refresh_normal);
                    break;

                case STATE_READY:
                    if (mState != STATE_READY) {
//                        mArrowImageView.clearAnimation();
//                        mArrowImageView.startAnimation(mRotateUpAnim);
//                        mHintTextView.setText(R.string.header_hint_refresh_ready);
                    }
                    break;

                case STATE_REFRESHING:
                    if (mState == STATE_READY) {
                        if (!mProgressAnim.isRunning()) {
                            mProgressAnim.start();
                        }
                    }
//                    mHintTextView.setText(R.string.header_hint_refresh_loading);
                    break;

                default:
                    break;
            }
        } else if (mHeaderType == GRADIENT_HEADER) {
            mGradientView.setVisibility(VISIBLE);
            mGradientHintTextView.setVisibility(VISIBLE);
            mGradientTxt.setText("");
            mGradientTxt.setBackgroundColor(ContextCompat.getColor(mContext,R.color.refresh_transparent));
            //新版本模仿某宝下拉
            if (state == STATE_REFRESHING) {
                mGradientView.clearAnimation();
            }
            switch (state) {
                case STATE_NORMAL:
                    //下拉可以刷新
                    if (mState == STATE_REFRESHING) {
                        mGradientView.clearAnimation();
                    }
                    mGradientView.setIsShowIcon(true);
                    mGradientHintTextView.setText(R.string.header_hint_refresh_normal);
                    break;

                case STATE_READY:
                    //松开可以刷新
                    if (mState != STATE_READY) {
                        mGradientView.setIsShowIcon(false);
                        mGradientHintTextView.setText(R.string.header_hint_refresh_ready);
                    }
                    break;

                case STATE_REFRESHING:
                    //正在刷新
                    mGradientView.setIsShowIcon(false);
                    mGradientHintTextView.setText(R.string.header_hint_refresh_loading);
                    mGradientView.startAnimation(refreshingAnimation);
                    break;
                case STATE_REFRESED:
                    //刷新完成
                    mGradientHintTextView.setVisibility(GONE);
                    mGradientView.clearAnimation();
                    mGradientView.setVisibility(GONE);
                    mGradientTxt.setText(txtSize);
                    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(mGradientTxt.getWidth(), mGradientTxt.getHeight());
                    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);//addRule参数对应RelativeLayout XML布局的属性
                    mGradientTxt.setLayoutParams(layoutParams);
                    mGradientTxt.setBackgroundColor(ContextCompat.getColor(mContext,R.color.refresh_top));
                    Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.refresh_show);
                    mGradientTxt.startAnimation(animation);
                    break;

                default:
                    break;
            }

        }

        mState = state;
    }

    /**
     * Set the header view visible height.
     *
     * @param height
     */
    public void setVisibleHeight(int height) {
        if (height < 0) {
            height = 0;
        }
        LayoutParams lp = (LayoutParams) mContainer.getLayoutParams();
        lp.height = height;
        mContainer.setLayoutParams(lp);
        if (mHeaderType == WINDWILL_HEADER) {
            float scale = (float) height / mFirstImgHeight;
            if (scale < 1) {

                //这个时候就是设置太阳的移动高度
                //需要设置太阳移动的高度

                //风车中心398：750 76：160
                //top = 76- 114/2 = 19
                //left = 398- 114/2 = 341

                //太阳 中心 250:750
                //top = 0.2*height

                //left = 250-38 = 232

                FrameLayout.LayoutParams params2 = (FrameLayout.LayoutParams) sunImg.getLayoutParams();
                //0.8*height - x*1.3*heaight
                params2.setMargins((int) (232 * WindowDispaly.getWidth() / 750f), (int) (mFirstImgHeight * 0.9f - scale * mFirstImgHeight * 0.8f), 0, 0);
                sunImg.setLayoutParams(params2);
            } else if (scale >= 1) {
                FrameLayout.LayoutParams params2 = (FrameLayout.LayoutParams) sunImg.getLayoutParams();
                params2.setMargins((int) (232 * WindowDispaly.getWidth() / 750f), (int) (mFirstImgHeight * 0.1f), 0, 0);
                sunImg.setLayoutParams(params2);
            }
        } else if (mHeaderType == GRADIENT_HEADER) {
            //控制下拉圆圈和箭头的下拉效果
            float scale = (float) height / mFirstImgHeight;
            scale = scale > 1.0f ? 1.0f : scale;
            int progress = (int) ((scale) * 100);
            mGradientView.setProgress(progress > 90 ? 90 : progress);
            mGradientView.setArrowAlpha((progress * 2) + 55);

        }

    }

    /**
     * Get the header view visible height.
     *
     * @return
     */
    public int getVisibleHeight() {
        return mContainer.getLayoutParams().height;
    }


    public void setRefreshTime(String time) {
        if (mHeaderType == COMMON_HEADER) {
            mHeaderTime.setText(time);
        }
    }

}
